<template>
  <g-form-wrap :title="title" :on-save-btn-click="onSaveBtnClick" v-loading.fullscreen.lock="pageLoading">
    <el-form
      ref="ruleForm"
      :model="formData"
      :rules="formRules"
      label-position="right"
      label-width="140px"
      inline
    >
      <div class="w-full">
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="登录名邮箱：" prop="backLoginname">
              <el-input
                v-model="formData.backLoginname"
                placeholder="请输入登录名邮箱"
                class="edit-item"
                clearable
              >
                <template #suffix>@zero2ipo.com.cn</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名：" prop="backUsername">
              <el-input
                v-model="formData.backUsername"
                placeholder="请输入用户姓名"
                class="edit-item"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="账号状态：" prop="accountstatus">
              <g-select
                v-model="formData.accountstatus"
                placeholder="请选择账号状态"
                class="edit-item"
                :options="[
                  { id: 1, name: '有效' },
                  { id: 2, name: '无效' }
                ]"
                :filterable="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 1.系统管理员 2.设计师 3.调研管理员 4.访客' -->
            <el-form-item label="角色：" prop="roleId">
              <el-radio-group v-model="formData.roleId">
                <el-radio v-for="item in roleList" :key="item.name" :label="item.id">{{
                  item.name
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="开始时间：" prop="joinDate">
              <el-date-picker
                v-model="formData.joinDate"
                :append-to-body="false"
                class="search-item"
                type="date"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD"
                value-format="x"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期时间：" prop="expiredDate">
              <el-date-picker
                v-model="formData.expiredDate"
                :append-to-body="false"
                class="search-item"
                type="date"
                placeholder="请选择到期时间"
                format="YYYY-MM-DD"
                value-format="x"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="12">
            <el-form-item label="权限：" prop="menuIdList">
              <el-tree
                :data="menuList"
                show-checkbox
                check-on-click-node
                node-key="id"
                :default-checked-keys="checkedMenuList"
                :props="defaultProps"
                @check="
                  (click, checked) => {
                    formData.menuIdList = [...checked.checkedKeys, ...checked.halfCheckedKeys]
                  }
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
        </el-row>
      </div>
    </el-form>
  </g-form-wrap>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, h } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Loading } from '@/components/Dialog/types'
import { useRoute, useRouter } from 'vue-router'
import elv from '@/utils/elValidation'
import { getBackUserByIdApi, addBackUserApi, updateBackUserApi } from '@/api/system'
import { Page } from '@/types/storeModule'
import { assign, cloneDeep, omit, replace } from 'lodash-es'
import dayjs from 'dayjs'
import { useStore } from 'vuex'

const route = useRoute()
const router = useRouter()
const store = useStore()
const isEditing = ref(false)
const ruleForm = ref<FormInstance>()
const roleList = ref([
  { id: 1, name: '系统管理员' },
  { id: 2, name: '设计师' },
  { id: 3, name: '调研管理员' },
  { id: 4, name: '访客' }
])
const defaultProps = ref({
  children: 'children',
  label: 'name'
})
let menuList = ref<any>([])
let checkedMenuList = ref<any>([])
let formData = ref(<
  {
    backUserId: string | number
    backLoginname: string
    backUsername: string
    accountstatus: string | number
    menuIdList: any
    roleId: any
    joinDate: string
    expiredDate: string
  }
>{
  backUserId: 0,
  backLoginname: '',
  backUsername: '',
  accountstatus: 1,
  menuIdList: [],
  roleId: 4,
  joinDate: '',
  expiredDate: ''
})
let pageLoading = ref<boolean>(true)
// 校验时间
const checkJoinDate = (required = true, msg = '请输入开始时间', value) => {
  const validJoinDate = (rule, value, callback) => {
    if (required) {
      if (!value) {
        callback(new Error(msg))
      } else if (dayjs(formData.value.expiredDate).isBefore(dayjs(formData.value.joinDate))) {
        callback(new Error('开始时间不能大于到期时间，请重新选择'))
      } else {
        callback()
      }
    } else {
      if (!value) {
        callback()
      } else if (dayjs(formData.value.expiredDate).isBefore(dayjs(formData.value.joinDate))) {
        callback(new Error('开始时间不能大于到期时间，请重新选择'))
      } else {
        callback()
      }
    }
  }
  return validJoinDate
}
const formRules = reactive<FormRules>({
  backLoginname: [{ required: true, message: '请输入登录名邮箱', trigger: 'change' }],
  backUsername: [{ required: true, message: '请输入用户姓名', trigger: 'change' }],
  joinDate: [{ required: true, message: '请输入开始时间', trigger: 'change' }],
  expiredDate: [{ required: true, message: '请输入到期时间', trigger: 'change' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
})

const id = route.query.id as string | number
const title = route.meta.title as string
isEditing.value = id > 0 ? true : false
// 编辑时
if (isEditing.value) {
  const getBackUserByIdFunc = async () => {
    const data = await getBackUserByIdApi({ id: id })
    formData.value = cloneDeep(omit(data.backuser, ['History', 'history', 'repeatKeys']))
    menuList.value = cloneDeep(data.menuList)
    // console.log('menulist===', menuList.value);

    checkedMenuList.value = data.menuIdList
    // console.log('menuIdList===', checkedMenuList.value);
    formData.value.roleId = cloneDeep(data.roleId)
    formData.value.joinDate = data.joinDate
    formData.value.expiredDate = data.expiredDate
    formData.value.backLoginname = replace(formData.value.backLoginname, '@zero2ipo.com.cn', '')
    // console.log('formData.value.menuIdList===', formData.value.menuIdList);\
    pageLoading.value = false
  }
  getBackUserByIdFunc()
}else{
  pageLoading.value = false
}
// 保存提交
const onSaveBtnClick = (loading: Loading) => {
  ruleForm.value?.validate((valid) => {
    if (valid) {
      if (dayjs(formData.value.expiredDate).isBefore(dayjs(formData.value.joinDate))) {
        ElMessage.warning('开始时间不能大于到期时间，请重新选择')
        return false
      }
      formData.value.backLoginname = formData.value.backLoginname + '@zero2ipo.com.cn'
      // console.log('formData.value===', formData.value)
      loading(true)
      if (isEditing.value) {
        updateBackUserApi(formData.value).then((res) => {
          if (res * 1 === 200) ElMessage.success('编辑成功')
        })
      } else {
        addBackUserApi(formData.value).then((res) => {
          if (res) {
            ElMessageBox({
              title: '添加成功',
              message: h('p', null, [
                h('span', null, '用户密码为： '),
                h('i', { style: 'color: teal' }, res)
              ]),
              confirmButtonText: '确认',
              type: 'success',
              draggable: true
            })
          }
        })
      }
      // 更新 store 中用户的信息
      store.dispatch('user/getUserInfoFunc')
      setTimeout(() => {
        loading(false)
        router.back()
      }, 100)
    } else {
      return false
    }
  })
}
</script>
